package com.lambkit.module.upms.auth.service;

import cn.hutool.core.util.StrUtil;
import com.lambkit.LambkitConsts;
import com.lambkit.auth.AuthConfig;
import com.lambkit.auth.service.AuthSessionService;
import com.lambkit.core.Lambkit;
import com.lambkit.core.http.ICookie;
import com.lambkit.core.http.IRequest;

/**
 * @author yangyong(孤竹行)
 */
public class UpmsSessionService implements AuthSessionService {
    @Override
    public String getId(IRequest request) {
        String sessionid = request.getParameter("tk");
        sessionid = StrUtil.isBlank(sessionid) ? request.getParameter("token") : sessionid;
        sessionid = StrUtil.isBlank(sessionid) ? request.getParameter("accessToken") : sessionid;
        sessionid = StrUtil.isBlank(sessionid) ? request.getParameter("sessionId") : sessionid;
        sessionid = StrUtil.isBlank(sessionid) ? request.getParameter("sessionid") : sessionid;
        if(StrUtil.isBlank(sessionid)) {
            AuthConfig config = Lambkit.config(AuthConfig.class);
            sessionid = request.getHeader(config.getHeader());
        }
        if(StrUtil.isBlank(sessionid)) {
            sessionid = request.getHeader(LambkitConsts.TOKEN);
        }
        sessionid = StrUtil.isBlank(sessionid) ? getCookie(request, "JSESSIONID") : sessionid;
        sessionid = StrUtil.isBlank(sessionid) ? (String) request.getAttribute("JSESSIONID") : sessionid;
//		if(StrUtil.isBlank(sessionid)) {
//			Subject subject = SecurityUtils.getSubject();
//	        Session session = subject.getSession();
//	        sessionid = session.getId().toString();
//		}
        return sessionid;
    }

    /**
     * Get cookie value by cookie name.
     */
    public String getCookie(IRequest request, String name) {
        ICookie cookie = getCookieObject(request, name);
        return cookie != null ? cookie.getValue() : null;
    }

    /**
     * Get cookie object by cookie name.
     */
    public ICookie getCookieObject(IRequest request, String name) {
        ICookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (ICookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
        }
        return null;
    }
}
